package lion.dev.net;

import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 该类获取系统中硬件网卡地址，和网卡对应的ipv4或ipv6地址，如果该网卡没有启用，或者是回路、虚拟的则过滤。
 *
 * @author lion
 * @date 2011-7-7
 */
public class LocalMac {

	private Log log = LogFactory.getLog(LocalMac.class);

	private List<Mac> macs = new ArrayList<>();
	private static LocalMac instance = new LocalMac();

	private LocalMac() {

		try {
			initNetwork();
		} catch (SocketException e) {
			log.error("init network fail:", e);
		}
	}

	private void initNetwork() throws SocketException {

		for (NetworkInterface ni : Collections.list(NetworkInterface.getNetworkInterfaces())) {

			if (ni.isVirtual() || ni.isLoopback() || !ni.isUp()) {
				continue;
			}

			Mac mac = new Mac();

			mac.setName(ni.getDisplayName());
			mac.setMac(foramt(ni.getHardwareAddress()));

			if (!mac.getMac().matches("(\\w{2}-){5}\\w{2}")) {
				continue;
			}

			for (InterfaceAddress ifa : ni.getInterfaceAddresses()) {
				if (ifa.getAddress().getHostAddress().matches("(\\w+:){7}[\\w%]+")) {
					mac.setIPV6(ifa.getAddress().getHostAddress());
				} else if (ifa.getAddress().getHostAddress().matches("((25[0-5]|2[0-4]\\d|1?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|1?\\d\\d?)")) {
					mac.setIPV4(ifa.getAddress().getHostAddress());
				}
			}
			macs.add(mac);
		}
	}

	private String foramt(byte[] bytes) {

		StringBuilder builder = new StringBuilder();
		for (byte i : bytes) {
			builder.append(String.format("%02X", i)).append("-");
		}

		return builder.toString().replaceAll("-$", "");
	}

	public List<Mac> getMACAddrs() {

		return macs;
	}

	public static List<Mac> getMacAddrs() {

		return instance.getMACAddrs();
	}

	public class Mac {

		private String name;
		private String mac;
		private String ipv4;
		private String ipv6;

		public String getName() {

			return name;
		}

		public void setName(String name) {

			this.name = name;
		}

		public String getMac() {

			return mac;
		}

		public void setMac(String mac) {

			this.mac = mac;
		}

		public String getIPV4() {

			return ipv4;
		}

		public void setIPV4(String ip4) {

			this.ipv4 = ip4;
		}

		public String getIPV6() {

			return ipv6;
		}

		public void setIPV6(String ip6) {

			this.ipv6 = ip6;
		}

	}
}
